// 配置请求基础URL
const BASE_URL = "https://localhost:5001/api/";

// 请求拦截器
const requestInterceptor = (options) => {
  // 获取token
  const token = uni.getStorageSync("token");

  // 合并请求头
  options.header = {
    ...options.header,
    Authorization: token ? `Bearer ${token}` : "",
    "Content-Type": "application/json",
  };

  // 拼接完整请求地址
  options.url = BASE_URL + options.url;

  return options;
};

// 响应拦截器
const responseInterceptor = (response) => {
  const { statusCode, data } = response;

  // 请求成功
  if (statusCode >= 200 && statusCode < 300) {
    return data;
  }

  // 401：未登录或token过期
  if (statusCode === 401) {
    uni.showToast({
      title: "请先登录",
      icon: "none",
    });
    // 跳转登录页
    setTimeout(() => {
      uni.navigateTo({
        url: "/pages/login/login",
      });
    }, 1500);
    return Promise.reject(new Error("未登录"));
  }

  // 其他错误
  uni.showToast({
    title: data.message || "请求失败",
    icon: "none",
  });
  return Promise.reject(data);
};

// 封装请求方法
const request = (options) => {
  options = requestInterceptor(options);

  console.log("发起请求详情:", {
    url: options.url,
    method: options.method,
    headers: options.header,
    data: options.data,
    rawData: JSON.stringify(options.data),
  });

  return new Promise((resolve, reject) => {
    uni.request({
      ...options,
      success: (res) => {
        console.log("请求响应:", {
          statusCode: res.statusCode,
          data: res.data,
          headers: res.header,
        });
        resolve(responseInterceptor(res));
      },
      fail: (err) => {
        console.error("请求失败:", err);
        uni.showToast({
          title: "网络错误",
          icon: "none",
        });
        reject(err);
      },
    });
  });
};

export default request;
